package cn.vendsystem.com.controller;


import cn.vendcommon.com.entity.Result;
import cn.vendcommon.com.entity.User;
import cn.vendcommon.com.entity.dto.DeductionAccountDTO;
import cn.vendcommon.com.entity.vo.UserVO;
import cn.vendcommon.com.utils.Md5Util;
import cn.vendcommon.com.utils.ThreadLocalUtil;
import cn.vendcommon.com.utils.UserContext;
import cn.vendsystem.com.service.UserService;
import cn.vendsystem.com.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private UserService userService;

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/userinfo")
    public Result<UserVO> userinfo() {
        Long userId = UserContext.getUserId();
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.findByUserId(userId), userVO);
        return Result.success(userVO);
    }

    @PostMapping("/userinfobyid")
    public Result<UserVO> userInfoById(@RequestParam("id") Long id) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.findByUserId(id), userVO);
        return Result.success(userVO);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/updatebaseinfo")
    public Result<UserVO> updateBaseInfo(@RequestBody User user) {
        userService.updateBaseInfo(user);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.findByUserId(Long.valueOf(user.getId())), userVO);
        return Result.success(userVO);
    }

    /**
     * 更新用户头像（上传到OSS）
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadAvatar(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传文件为空");
        }
        log.info("文件上传：{}", file);
        try {
            // 原始文件名
            String orginaiFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀
            String extension = orginaiFilename.substring(orginaiFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = "userAvatar/" + UUID.randomUUID().toString() + extension;
            // 文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            // 保存头像地址(删除旧头像地址)
            userService.updateAvatar(filePath);
            // 返回路径
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("上传失败");
        }
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params) {
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) ||
                !StringUtils.hasLength(newPwd) ||
                !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }

        Long userId = UserContext.getUserId();
        User loginUser = userService.findByUserId(userId);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");
        }
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写的新密码不一样");
        }
        //更新密码
        userService.updatePwd(newPwd);
        return Result.success();
    }

    /**
     * 用户列表
     */
    @GetMapping("/list")
    public Result<List<User>> listUsers() {
        List<User> users = userService.findAll();
        return Result.success(users);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        userService.addUser(user);
        return Result.success();
    }

    /**
     * 更新用户
     */
    @PutMapping("/update")
    public Result updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return Result.success();
    }

    /**
     * 修改用户状态
     */
    @PatchMapping("/status/{id}")
    public Result changeStatus(@PathVariable Integer id, @RequestParam Integer status) {
        userService.changeStatus(id, status);
        return Result.success();
    }

    /**
     * 扣减用户金额
     * @param params
     * @return
     */
    @PostMapping("/deductionaccount")
    public Result deductionUserAmount(@RequestBody DeductionAccountDTO deductionAccountDTO) {
        userService.deductionUserBalance(deductionAccountDTO.getId(), deductionAccountDTO.getAccount());
        return Result.success();
    }
}